package com.ddatsh.transaction.core;

import java.util.Date;

import com.ddatsh.transaction.core.exception.TransException;
import com.ddatsh.transaction.core.lifecycle.executor.TranscationExecutor;
import com.ddatsh.transaction.core.lifecycle.factory.TransContextFactory;
import com.ddatsh.transaction.core.model.ApplicationErrorCode;
import com.ddatsh.transaction.core.model.Request;
import com.ddatsh.transaction.core.model.Response;
import com.ddatsh.transaction.core.model.TransContext;
import com.ddatsh.transaction.core.provider.JsonConvertProvider;

public class MainEntryImpl implements MainEntry {
	
	private TransContextFactory transContextFactory;
	private TranscationExecutor transcationExecutor;
	private JsonConvertProvider jsonConvertProvider;
	
	public Response submit(Request request) {
 		return service(request);
	}

	private Response service(Request request) {
		Response response = null;
		request.setArrivalTime(new Date());
		if (response == null) {
			TransContext transContext = transContextFactory
					.createTransContext(request);
			transcationExecutor.doTranscation(transContext);
			TransException exception = transContext.getException();
			// 交易环节产生异常信息，则直接返回错误给用户
			if (exception != null) {
				response = buildResponse(request, exception.getCode(),
						exception.getMessage());
			} else {
				response = transContext.getResponse();
			
				if (response == null) {
					response = buildResponse(request,
							ApplicationErrorCode.RESPONSE_IS_NULL,
							"系统异常：返回对象为空！");
				} else {
					if (response.getResponseBody() == null) {
						response = buildResponse(request,
								ApplicationErrorCode.RESPONSE_BODY_IS_NULL,
								"系统异常，返回对象主体为空！");
					}
				}
			}
		}
		return response;
	}

	/*
	 * 异常信息构件响应报文
	 */
	private Response buildResponse(Request request, String errCode,
			String errMsg) {
		Response response = new Response(request);
		response.setErrorCode(errCode);
		response.setErrorMsg(errMsg);
		response.setStatus(Response.STATUS_COMPLETE);
		return response;
	}

	public TransContextFactory getTransContextFactory() {
		return transContextFactory;
	}

	public void setTransContextFactory(TransContextFactory transContextFactory) {
		this.transContextFactory = transContextFactory;
	}

	public TranscationExecutor getTranscationExecutor() {
		return transcationExecutor;
	}

	public void setTranscationExecutor(TranscationExecutor transcationExecutor) {
		this.transcationExecutor = transcationExecutor;
	}

	public JsonConvertProvider getJsonConvertProvider() {
		return jsonConvertProvider;
	}

	public void setJsonConvertProvider(JsonConvertProvider jsonConvertProvider) {
		this.jsonConvertProvider = jsonConvertProvider;
	}
		
}
